package com.suxiaofang.library.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suxiaofang.library.common.Result;
import com.suxiaofang.library.entity.Book;
import com.suxiaofang.library.entity.Files;
import com.suxiaofang.library.entity.User;

import com.suxiaofang.library.service.impl.BookServiceImpl;
import com.suxiaofang.library.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

/**
 * 文件名：BookController
 * 创建者：蔡江鸿
 * 创建时间：2022/9/13-21:44
 * 描述：
 */
@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookServiceImpl bookService;
    /**
     * 新增和更新
     * @param book
     * @return
     */
    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Book book) {
        return Result.success(bookService.saveOrUpdate(book));
    }


    @GetMapping("/count")
    public Result bookCount(){
        return Result.success(bookService.count());
    }
    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(bookService.list());
    }


    @PostMapping("/update")
    public Result update(@RequestBody Book book) {
        return Result.success(bookService.updateById(book));
    }
    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(bookService.removeById(id));
    }

    /**
     * 批量删除删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(bookService.removeByIds(ids));
    }

    /**
     * 分页查询
     * mybatis-plus 查询
     * //        @RequestParam(defaultValue = "") String nickname
     * //        queryWrapper.or().like(!Strings.isEmpty(nickname),"nickname", nickname);
     *
     * @return
     * @RequestParam Limit第-个参数.=(pageNum-1)*pageSize
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String author,
                           @RequestParam(defaultValue = "") String isbn
    ) {
        IPage<Book> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!Strings.isEmpty(name),"name", name);
        queryWrapper.like(!Strings.isEmpty(author),"author",author);
        queryWrapper.like(!Strings.isEmpty(isbn),"isbn", isbn);
        queryWrapper.orderByDesc("id");
        return Result.success(bookService.page(page, queryWrapper));
    }


    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Book> list = bookService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名   在entity 起也可以@Alias
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "图书书名");
        writer.addHeaderAlias("author", "图书作者");
        writer.addHeaderAlias("press", "出版社");
        writer.addHeaderAlias("isbn", "国际通用标准书号");
        writer.addHeaderAlias("category", "图书类别");
        writer.addHeaderAlias("stock", "库存");
        writer.addHeaderAlias("lending", "借出数量");
        writer.addHeaderAlias("surplus", "剩余数量");
        writer.addHeaderAlias("createTime", "创建时间");

        // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("图书列表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        HashMap<String, String> headerAlias = new HashMap<>(8);
        headerAlias.put("图书书名", "name");
        headerAlias.put("图书作者", "author");
        headerAlias.put("出版社", "press");
        headerAlias.put("国际通用标准书号", "isbn");
        headerAlias.put("图书类别", "category");
        headerAlias.put("库存", "stock");
        headerAlias.put("借出数量", "lending");
        headerAlias.put("剩余数量", "surplus");
        reader.setHeaderAlias(headerAlias);

        List<Book> list = reader.readAll(Book.class);

        System.out.println(list);

        //上传的excel数据,保存到数据库中
        bookService.saveBatch(list);
        return Result.success(true);
    }

}
